let express = require('express');
let db = require('../tools/db');
let to = require('../tools/to');

let router = express.Router();

router.post("/courses", async (req, res) => {
    let {
        type= 1,
        area= "",
        grade= "",
        subject= "",
        category= "",
        price= "desc",
        page= 1,
        pagesize= 9
    } = req.body;   

    let start = (page-1)*pagesize;//起始记录位置

    let str = '';
    if( area ){
        str += `  AND area_name = '${area}'`;
    }
    if( grade ){
        str += `  AND grade_name = '${grade}'`;
    }
    if( subject ) {
        str += `  AND subject_name = '${subject}'`;
    }
    if( category ){
        str += `  AND category_name = '${category}'`;
    }
    let sql = `SELECT
	id,
	cid,
	title,
	price,
	concat( '/uploads/course/', image_src ) AS image_src,
	type_name,
	area_name,
	grade_name,
	subject_name,
	category_name 
FROM
	e_course 
WHERE
	type = ${type} ${str}
ORDER BY
	price ${price} 
	LIMIT ${start},${pagesize}`

    let sql2  = `select count(id) as totalnum from e_course where type = ${type} ${str}`;
    let [{totalnum}] = await db.query(sql2,[]);//[{totalnum:8}]
    
    // let a = await db.query(sql,[]);
    // res.json({code:200,data:a,msg:'列表数据成功'})
    // console.log(sql);
    let [err,result] = await to(db.query(sql,[]));
    if(!err){
        res.json({code:200,data:{totalnum,page:parseInt(page),pagesize:parseInt(pagesize),result},msg:"列表数据成功"});
    }else{
        res.json({code:500,data:err,msg:"数据库查询失败"});
    }
})
// function to(promise) {
//     return promise.then((data)=>{
//         return [null,data]
//     }).catch((err)=>{

//         return [err]
//     })
// }

//地区接口 /areas
router.get('/areas',async (req,res)=>{
    let sql = `select * from e_area`;
    let a =await db.query(sql,[]);
    res.json({code:200,data:a,msg:"地区列表数据成功"})
})

//年级接口 /grades
router.get('/grades',async (req,res)=>{
    let sql = `select * from e_grade`;
    let b = await db.query(sql,[]);
    res.json({code:200,data:b,msg:"年级列表数据成功"});
})
//学科接口 /subjects
router.get('/subjects',async (req,res)=>{
    let sql = `select * from e_subject`;
    let c = await db.query(sql,[]);
    res.json({code:200,data:c,msg:"学科列表数据成功"});
})
//考试类别接口 /categorys
router.get('/categorys',async (req,res)=>{
    let sql = `select * from e_category`;
    let d = await db.query(sql,[]);
    res.json({code:200,data:d,msg:"考试类别数据成功"});
})
module.exports = router;